package com.taobaolite.transaction;

import com.taobaolite.user.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class TransactionService {
    private final TransactionRepository transactionRepo;
    private final UserRepository userRepo;
    private final UserService userService;

    @Autowired
    public TransactionService(TransactionRepository transactionRepo, UserRepository userRepo, UserRepository userRepo1, UserService userService) {
        this.transactionRepo = transactionRepo;
        this.userRepo = userRepo1;
        this.userService = userService;
    }

    public List<TransactionBody> getTransaction(Long userId) {
        User user = userRepo.findById(userId)
                .orElseThrow(() -> new ResponseStatusException(
                        HttpStatus.NOT_FOUND,
                        "User with ID " + userId + " does not exist."
                ));

        List<TransactionBody> transactionBodyList = new ArrayList<TransactionBody>();
        List<Transaction> transactionList;

        // For admin user
        if (user.getType() == UserType.ADMIN) {
            transactionList = transactionRepo.findAll();
        } else { // For normal user
            transactionList = transactionRepo.findByUserId(userId);
        }

        // Construct transactionBodyList from transactionList
        for (Transaction t : transactionList) {
            UserBody userFrom = userService.generateUserBody(t.getTransactionId().getUserFrom().getUserId());
            UserBody userTo = userService.generateUserBody(t.getTransactionId().getUserTo().getUserId());
            TransactionBody transactionBody = new TransactionBody(
                    userFrom,
                    userTo,
                    t.getTransactionId().getTime(),
                    t.getTotal()
            );
            transactionBodyList.add(transactionBody);
        }

        return transactionBodyList;
    }
}
